﻿
package com.ostrich.manpower.controller;

import java.io.FileInputStream;


import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.ostrich.manpower.common.DateUtil;
import com.base.util.HtmlUtil;
import com.base.web.BaseAction;
import com.ostrich.manpower.bean.TostHrBaseinfo;
import com.ostrich.manpower.bean.TostHrZhongheinfo;
import com.ostrich.manpower.common.ImportUtil;
import com.ostrich.manpower.service.impl.TostHrBaseinfoService;
import com.ostrich.manpower.service.impl.TostHrZhongheinfoService;

/**
 * ClassName: Controller <br/>
 * date: 2013-5-9 下午03:07:38 <br/>
 * 
 * @author wangyinan
 * @version
 */
@Controller
@RequestMapping("/tostHrZhongheinfo")
public class TostHrZhongheinfoController extends BaseAction
{
	private final static Logger log= Logger.getLogger(TostHrZhongheinfoController.class);

	// Servrice start
	@Autowired(required=false) //自动注入，不需要生成set方法了，required=false表示没有实现类，也不会报错。
	private TostHrZhongheinfoService<TostHrZhongheinfo> tostHrZhongheinfoService; 
	
	@Autowired(required=false) //自动注入，不需要生成set方法了，required=false表示没有实现类，也不会报错。
	private TostHrBaseinfoService<TostHrBaseinfo> tostHrBaseinfoService; 
	
	/**
	 * ilook 首页
	 * @param url
	 * @param classifyId
	 * @return
	 */
	@RequestMapping("/list")
	public ModelAndView  list(TostHrZhongheinfo tostHrZhongheinfo,HttpServletRequest request) throws Exception{
		Map<String,Object>  context = getRootMap();
		List<TostHrZhongheinfo> dataList = tostHrZhongheinfoService.queryByList(tostHrZhongheinfo);
		//设置页面数据
		context.put("dataList", dataList);
		return forword("manpower/tabTostHrZhongheinfo",context); 
	}
	
	/**
	 * json 列表页面
	 * @param url
	 * @param classifyId
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/dataList") 
	public void  dataList(TostHrZhongheinfo tostHrZhongheinfo,HttpServletResponse response) throws Exception{
		tostHrZhongheinfo.setHzhMont(DateUtil.getYearMonthByDate(tostHrZhongheinfo.getHzhMont()));
		List<TostHrZhongheinfo> dataList = tostHrZhongheinfoService.queryByMap(tostHrZhongheinfo);
		for(TostHrZhongheinfo ud: dataList){
			//这里可以做数据封装到对象中。
		}
		//设置页面数据
		Map<String,Object> jsonMap = new HashMap<String,Object>();
		jsonMap.put("total",tostHrZhongheinfo.getPager().getRowCount());
		jsonMap.put("rows", dataList);
		HtmlUtil.writerJson(response, jsonMap);
	}


	/**
	 * 添加或修改数据
	 * @param url
	 * @param classifyId
	 * @return
	 * @throws Exception 
	 */
/*	@RequestMapping("/save")
	public void save(TostHrZhongheinfo bean,HttpServletResponse response) throws Exception{
		Map<String,Object>  context = new HashMap<String,Object>();
		tostHrZhongheinfoService.updateBySelective(bean);
		sendSuccessMessage(response, "保存成功~");
	}*/
	@RequestMapping("/save")
	public void save(TostHrZhongheinfo bean,HttpServletResponse response,HttpServletRequest request) throws Exception{
		Map<String,Object>  context = new HashMap<String,Object>();
		//判断是修改还是添加
		//添加
		if(bean.getId()==null){
			String hrCode = bean.getHrCode();
			TostHrBaseinfo baseinfo = tostHrBaseinfoService.getBaseinfoByHrCode(hrCode);
			//先判断基础表中是否有此人
			//有人
			String hrName = bean.getHrName().trim();
			if(null != hrName && !hrName.equals(baseinfo.getHrName())){
				System.out.println("添加失败:"+bean.getHrCode()+"与"+bean.getHrName()+"不匹配");
				sendFailureMessage(response, "添加失败:"+bean.getHrCode()+"与"+bean.getHrName()+"不匹配");
			}
			else if(null!=baseinfo){
				//在判断该月该人是不是已经存在数据
						String mont = bean.getHzhMont();
						String setmont = mont.length()>8?DateUtil.getYearMonthByDate(mont):mont;
						bean.setHzhMont(setmont);
						TostHrZhongheinfo zhonghe = tostHrZhongheinfoService.queryZhongheByhrid(baseinfo.getId(), bean.getHzhMont());
				 //无数据
				  if(null ==zhonghe){
					bean.setHrId(baseinfo.getId());
					tostHrZhongheinfoService.add(bean);
					sendSuccessMessage(response, "保存成功~");
				  	}
				  //有数据
				  else {
				    String faileMessage =  "添加失败："+baseinfo.getHrName()+bean.getHzhMont()+"月的数据以经存在，请选择修改";
				    System.out.println(faileMessage);
					sendFailureMessage(response,faileMessage);
				   }
			}
			else{
				//无人
				sendFailureMessage(response, "添加失败：编号为"+hrCode+"的员工不存在");
			}
		}
		//修改
		else{
			String emont = bean.getHzhMont();
		    String esetmont = emont.length()>8?DateUtil.getYearMonthByDate(emont):emont;
			bean.setHzhMont(esetmont);
			tostHrZhongheinfoService.update(bean);
			sendSuccessMessage(response, "更新成功~");
		}
	}
	
	
	@RequestMapping("/getId")
	public void getId(Integer id,HttpServletResponse response) throws Exception{
		Map<String,Object>  context = getRootMap();
		TostHrZhongheinfo bean  = tostHrZhongheinfoService.queryById(id);
		if(bean  == null){
			sendFailureMessage(response, "没有找到对应的记录!");
			return;
		}
		context.put(SUCCESS, true);
		context.put("data", bean);
		HtmlUtil.writerJson(response, context);
	}
	
	@RequestMapping("/delete")
	public void delete(Integer[] id,HttpServletResponse response) throws Exception{
		tostHrZhongheinfoService.delete(id);
		sendSuccessMessage(response, "删除成功");
	}
	
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public ModelAndView upload(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) throws IOException {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		// 得到上传的文件
		MultipartFile mFile = multipartRequest.getFile("excelPath");
		// 得到上传服务器的路径
		String path = request.getSession().getServletContext()
				.getRealPath("/WEB-INF/upload/");
		// 得到上传的文件的文件名
		String filename = mFile.getOriginalFilename();
		InputStream inputStream = mFile.getInputStream();
		byte[] b = new byte[1048576];
		int length = inputStream.read(b);
		path += "\\" + filename;
		// 文件流写到服务器端
		FileOutputStream outputStream = new FileOutputStream(path);
		outputStream.write(b, 0, length);
		inputStream.close();
		outputStream.close();
		request.setAttribute("path", path);
		return new ModelAndView("forward:/tostHrZhongheinfo/upimport.do");
	}

	@RequestMapping(value = "/upimport")
	public ModelAndView upimport(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map<String, Object> context = getRootMap();
		String filepath = (String) request.getAttribute("path");
		try {
			InputStream fis = new FileInputStream(filepath);
			HSSFSheet sh = ImportUtil.getSheet(fis);

			String msg = tostHrZhongheinfoService.setZhongheiBySheet(sh);
			msg=(msg!=null && msg.trim().length()>0)?"您已经成功导入。但是还有："+msg:"您已经导入成功请查看。";
			request.setAttribute("success", "您已经导入成功请查看!");
			request.setAttribute("msg",msg);
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("msg", "导入失败，请查看xls文件是否格式正确");
		}
		request.setAttribute("url", request.getContextPath()
				+ "/tostHrZhongheinfo/list.do");
		return forword("penmsg", context);
	}
}
